package com.tn.service;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.tn.bo.ApplicationNews;
import com.tn.bo.ClientSupplierData;
import com.tn.bo.Company;
import com.tn.bo.CreditMemo;
import com.tn.bo.CreditMemoLineItem;
import com.tn.bo.Currency;
import com.tn.bo.Invoice;
import com.tn.bo.InvoiceLineItem;
import com.tn.bo.LastUserLogin;
import com.tn.bo.POHeader;
import com.tn.bo.POLineItem;
import com.tn.bo.POSplitLineItem;
import com.tn.bo.Payment;
import com.tn.bo.UnitOfMeasure;
import com.tn.bo.UserLoginDetails;
import com.tn.bo.UserProfile;
import com.tn.bo.UserRegMapping;

public class OfyDataService {

	static {
		// Register All Entities Here.
		OfyDataService.getInstance().registerEntity(UserLoginDetails.class);
		OfyDataService.getInstance().registerEntity(UserProfile.class);
		OfyDataService.getInstance().registerEntity(UserRegMapping.class);
		
		OfyDataService.getInstance().registerEntity(POHeader.class);
		OfyDataService.getInstance().registerEntity(POLineItem.class);
		OfyDataService.getInstance().registerEntity(POSplitLineItem.class);
		OfyDataService.getInstance().registerEntity(Currency.class);
		OfyDataService.getInstance().registerEntity(UnitOfMeasure.class);
		
		OfyDataService.getInstance().registerEntity(Invoice.class);
		OfyDataService.getInstance().registerEntity(InvoiceLineItem.class);
		OfyDataService.getInstance().registerEntity(CreditMemo.class);
		OfyDataService.getInstance().registerEntity(CreditMemoLineItem.class);
		OfyDataService.getInstance().registerEntity(Payment.class);
		
		OfyDataService.getInstance().registerEntity(LastUserLogin.class);
		OfyDataService.getInstance().registerEntity(ApplicationNews.class);
		
		OfyDataService.getInstance().registerEntity(Company.class);
		OfyDataService.getInstance().registerEntity(ClientSupplierData.class);
		
	}
	
	private OfyDataService(){}
	
	private static OfyDataService instance;
	
	public static OfyDataService getInstance(){
		if(instance == null){
			instance = new OfyDataService();
		}
		
		return instance;
	}
	
	public Objectify getOfyService(){
		return ObjectifyService.begin();
	}
	
	public Objectify beginOfyTransaction(){
		return ObjectifyService.beginTransaction();
	}
	
	public boolean commitOfyTransaction(Objectify ofyTxObj){
		try{
			ofyTxObj.getTxn().commit();
			return true;
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if(ofyTxObj.getTxn().isActive()){
				ofyTxObj.getTxn().rollback();
			}
		}
		
		return false;
	}
	
	public void registerEntity(Class<?> clazz){
		ObjectifyService.register(clazz);
	}
}
